import { shallowRef, reactive } from "vue"
import { ElNotification } from "element-plus"
import { getAxios } from "/axios"
import { useBasis } from "./basis"
function formatModules(module) {
	return {
		formData: {},
		channel: "api",
		afterGetData: () => {},
		...module,
	}
}
let id = ""
function useInfo(modules) {
	const { formData: moduleFormData, channel, afterGetData, url } = formatModules(modules)
	const loading = shallowRef(true)
	const formData = reactive(Object.assign({}, moduleFormData))
	async function reload() {
		loading.value = true
		try {
			let result = await getAxios(url, { id }, { channel })
			if (typeof afterGetData === "function") {
				result = (await afterGetData(result)) || result
			}
			loading.value = false
			Object.keys(result).forEach(key => (formData[key] = result[key]))
		} catch (error) {
			loading.value = false
			ElNotification({ message: error, type: "error" })
			console.error(error)
		}
	}
	function onClose() {
		loading.value = false
		Object.keys(formData).forEach(key => (formData[key] = moduleFormData[key]))
	}
	return {
		loading,
		formData,
		reload,
		onClose,
	}
}
export function usePupopInfo(modules) {
	const basis = useBasis()
	const route = useRoute()
	const { loading, formData: moduleFormData, reload, onClose } = useInfo(modules)
	const visible = shallowRef(false)
	let query = {}
	function init(rowId, argQuery) {
		query = Object.assign({}, argQuery)
		id = rowId || route.query.id + ""
		visible.value = true
		reload()
	}
	return {
		...basis,
		query,
		loading,
		visible,
		formData: moduleFormData,
		reload,
		onClose,
		init,
	}
}
export function usePageInfo(modules) {
	const basis = useBasis()
	const route = useRoute()
	const { loading, formData: moduleFormData, reload, onClose } = useInfo(modules)
	let query = {}
	onActivated(() => {
		id = route.query.id + ""
		query = Object.assign({}, route.query)
		reload()
	})
	return {
		...basis,
		query,
		loading,
		formData: moduleFormData,
		reload,
		onClose,
	}
}
